package com.qys.livesMall.navy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.navy.common.Constant;
import com.qys.livesMall.navy.mapper.H2NavyLanguageManageMapper;
import com.qys.livesMall.navy.model.dto.task.AddGoodsComment;
import com.qys.livesMall.navy.model.entity.H2NavyLanguageManage;
import com.qys.livesMall.navy.model.entity.NavyTask;
import com.qys.livesMall.navy.model.entity.NavyTaskDetail;
import com.qys.livesMall.navy.service.NavyGoodsCommentService;
import com.qys.livesMall.navy.service.NavyTaskDetailService;
import com.qys.livesMall.navy.service.NavyTaskService;
import com.qys.livesMall.navy.task.TaskInter;
import com.qys.livesMall.product.mapper.H2ProductGoodsinfoMapper;
import com.qys.livesMall.shop.mapper.H2ShopBaseMapper;
import com.qys.livesMall.shop.mapper.ShopGoodsInfoMapper;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuMapper;
import com.qys.livesMall.shop.mapper.ShopOrderSkuMapper;
import com.qys.livesMall.shop.modal.entity.ShopGoodsInfo;
import com.qys.livesMall.shop.modal.entity.ShopGoodsSku;
import com.qys.livesMall.shop.modal.entity.ShopOrderComment;
import com.qys.livesMall.shop.modal.entity.ShopOrderSku;
import com.qys.livesMall.shop.service.ShopGoodsInfoService;
import com.qys.livesMall.shop.service.ShopGoodsSkuService;
import com.qys.livesMall.shop.service.ShopOrderCommentService;
import com.qys.livesMall.shortVideo.model.dto.app.AppUserCommentDTO;
import com.tencentcloudapi.iot.v20180123.models.AppUser;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class NavyGoodsCommentServiceImpl implements NavyGoodsCommentService {

    @Resource
    private MessageServer messageServer;

    @Resource
    private NavyTaskService navyTaskService;

    @Resource
    private H2NavyLanguageManageMapper h2NavyLanguageManageMapper;

    @Resource
    private ShopGoodsSkuMapper shopGoodsSkuMapper;

    @Resource
    private NavyTaskDetailService navyTaskDetailService;

    @Resource
    private H2AppUserMapper h2AppUserMapper;
    @Resource
    private ShopOrderCommentService commentService;
    @Resource
    private ShopGoodsSkuService goodsSkuService;
    @Resource
    private ShopGoodsInfoService goodsInfoService;

    @Resource
    @Lazy
    private TaskInter taskInter;

    @Override
    public R buildTask(AddGoodsComment param) {
        if (param == null || CollectionUtils.isEmpty(param.getNavyIds())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }

        NavyTask navyTask = new NavyTask();
        navyTask.setTaskType(Constant.TaskType.GOODS_COMMENT);
        navyTask.setTaskName("商品评论");
        navyTask.setTaskParam(JSONObject.toJSONString(param));
        navyTask.setTaskStatus(Constant.TaskStatus.RUNNING);
        navyTask.setTaskStartTime(LocalDateTime.now());
        navyTask.setCreateDate(LocalDateTime.now());
        navyTask.setUpdDate(LocalDateTime.now());
        //创建任务明细
        List<NavyTaskDetail> detailList = new ArrayList<>();
        for (int i = 0; i < param.getNavyIds().size(); i++) {
            NavyTaskDetail detail = new NavyTaskDetail();
            detail.setTaskId(navyTask.getId());
            detail.setTaskType(navyTask.getTaskType());
            detail.setSort(i + 1);
            detail.setNavyIds(JSONObject.toJSONString(Collections.singletonList(param.getNavyIds().get(i))));
            detail.setCreateDate(LocalDateTime.now());
            detail.setTaskStatus(Constant.TaskDetailStatus.NO_START);

            List<Long> shopGoodsSkuId = getCommentGoodsId(param);
            detail.setShopGoodsSkuIds(JSONObject.toJSONString(shopGoodsSkuId));
            detailList.add(detail);
        }
        navyTaskDetailService.batchSave(detailList);
        return R.ok();
    }

    private List<Long> getCommentGoodsId(AddGoodsComment param) {
        List<Long> newShopOrderSkus = new ArrayList<>();
        LambdaQueryWrapper<ShopGoodsSku> query;
        List<ShopGoodsSku> shopGoodsSkus;
        switch (param.getType()){
//          多店随机
            case 1:
                if ( CollectionUtils.isEmpty(param.getShopList())) {
                    throw new QysException(MessageUtils.message(ExceptionEnum.PARAM_IS_ERROR.getMsg()));
                }
                query = Wrappers.lambdaQuery(ShopGoodsSku.class)
                        .in(ShopGoodsSku::getShopId, param.getShopList());
                shopGoodsSkus = shopGoodsSkuMapper.selectList(query);
                Map<Long, List<ShopGoodsSku>> collect = shopGoodsSkus.stream()
                        .collect(Collectors.groupingBy(ShopGoodsSku::getShopId, Collectors.toList()));
                for (List<ShopGoodsSku> shopGoodsSkuList : collect.values()) {
                    int index = (int) (Math.random()* shopGoodsSkuList.size());
                    if (index==shopGoodsSkuList.size()){
                        index=index-1;
                    }
                    ShopGoodsSku shopGoodsSku = shopGoodsSkuList.get(index);
                    newShopOrderSkus.add(shopGoodsSku.getId());
                }
                break;
            case 2:
                if ( CollectionUtils.isEmpty(param.getShopList()) || CollectionUtils.isEmpty(param.getSkuIds())) {
                    throw new QysException(MessageUtils.message(ExceptionEnum.PARAM_IS_ERROR.getMsg()));
                }
               query = Wrappers.lambdaQuery(ShopGoodsSku.class)
                        .in(ShopGoodsSku::getShopId, param.getShopList())
                        .in(ShopGoodsSku::getSkuId, param.getSkuIds());
                shopGoodsSkus = shopGoodsSkuMapper.selectList(query);
                newShopOrderSkus = shopGoodsSkus.stream().map(ShopGoodsSku::getId).distinct().collect(Collectors.toList());
                break;
            case 3:
                if (CollectionUtils.isEmpty(param.getSkuIds())) {
                    throw new QysException(MessageUtils.message(ExceptionEnum.PARAM_IS_ERROR.getMsg()));
                }
                query = Wrappers.lambdaQuery(ShopGoodsSku.class)
                        .in(ShopGoodsSku::getSkuId, param.getSkuIds());
                shopGoodsSkus = shopGoodsSkuMapper.selectList(query);
                Map<Long, List<ShopGoodsSku>> skuInfoMap = shopGoodsSkus.stream()
                        .collect(Collectors.groupingBy(ShopGoodsSku::getSkuId, Collectors.toList()));
                for (List<ShopGoodsSku> shopGoodsSkuList : skuInfoMap.values()) {
                    int index = (int) (Math.random()* shopGoodsSkuList.size());
                    ShopGoodsSku shopGoodsSku = shopGoodsSkuList.get(index);
                    newShopOrderSkus.add(shopGoodsSku.getId());
                }
                break;
            default:
        }
        return newShopOrderSkus;
    }

    @Override
    @Async
    public void exc(Long taskDetailId) {
        NavyTaskDetail detail = navyTaskDetailService.getById(taskDetailId);
        if (detail == null) {
            return;
        }
        List<Long> goodsSkuIds = JSONArray.parseArray(detail.getShopGoodsSkuIds()).toList(Long.class);
        String userId = JSONArray.parseArray(detail.getNavyIds()).get(0).toString();
        H2AppUser appUser = h2AppUserMapper.selectById(userId);
        try {
            //            根据短视频数量随机查询短视频评论
            LambdaQueryWrapper<H2NavyLanguageManage> query = Wrappers.lambdaQuery(H2NavyLanguageManage.class);
//          水军语言类型（0：水军弹幕 1：水军商品评论 2：水军短视频评论）
            query.eq(H2NavyLanguageManage::getType, 1)
                    .last(" ORDER BY RAND() ")
                    .last(" LIMIT " + goodsSkuIds.size());

            List<H2NavyLanguageManage> h2NavyLanguageManages = h2NavyLanguageManageMapper.selectList(query);

            for (int i = 0; i < goodsSkuIds.size(); i++) {
                H2NavyLanguageManage languageManage;
                if (i >= h2NavyLanguageManages.size()) {
                    languageManage = h2NavyLanguageManages.get(h2NavyLanguageManages.size()-1);
                }else{
                    languageManage = h2NavyLanguageManages.get(i);
                }
                ShopOrderComment orderComment = new ShopOrderComment();
                //查询商品
                ShopGoodsSku goodSku = goodsSkuService.getById(goodsSkuIds.get(i));
                ShopGoodsInfo goodsInfo = goodsInfoService.getById(goodSku.getShopGoodsId());
                orderComment.setType("1");
                orderComment.setGoodsId(goodsInfo.getId().toString());
                orderComment.setGoodsName(goodsInfo.getGoodsName());
                orderComment.setSkuName(goodSku.getSkuName());
                orderComment.setShopId(goodsInfo.getShopId()+"");
                orderComment.setUserAvatar(appUser.getAvatar());
                orderComment.setUserName(appUser.getNickName());
                orderComment.setUserId(appUser.getId());
                orderComment.setRating("1");
                orderComment.setEnable("1");
                orderComment.setDeleted(false);

                orderComment.setCreatedTime(System.currentTimeMillis());
                orderComment.setUpdatedTime(System.currentTimeMillis());

                if (languageManage != null) {
                    orderComment.setContent(languageManage.getContent());
                }
                commentService.save(orderComment);
            }

        } catch (Exception e) {
            detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
            detail.setTaskDate(LocalDateTime.now());
            navyTaskDetailService.upById(detail);
            return;
        }

        detail.setTaskStatus(Constant.TaskDetailStatus.END_SUCCESS);
        navyTaskDetailService.upById(detail);
        //同步主任务状态
        boolean end = navyTaskService.watchTaskEnd(detail.getTaskId());
        if (end) {
            return;
        }
        //获取下一个任务
        NavyTaskDetail nextDetail = navyTaskDetailService.getNextDetail(detail.getTaskId());
        if (nextDetail != null) {
            taskInter.addGoodsCommentTask(RandomUtil.randomInt(600, 5400), nextDetail.getId());
        }
    }
}
